package com.flute.haflute.net.messaging;

import com.flute.haflute.common.ClusterConstants;
import com.flute.haflute.common.ClusterContext;

/**
 * 消息的工厂类，实现通用消息的工厂
 */
public class MessageFactory {

	private static Message heartBeatMessage = new Message(
			ClusterContext.getLocalAddress(), Message.MessageType.HB.name(),
			Message.Verb.HEARTBEARTING, new byte[0]);

	private static Message heartBeatAckMessage = new Message(
			ClusterContext.getLocalAddress(), Message.MessageType.HBACK.name(),
			Message.Verb.HEARTBEARTING, new byte[0]);

	private static Message heartBeatAck2Message = new Message(
			ClusterContext.getLocalAddress(),
			Message.MessageType.HBACK2.name(), Message.Verb.HEARTBEARTING,
			new byte[0]);

	public static Message getHeartBeatMessage() {
		return heartBeatMessage;
	}

	public static Message getHeartBeatAckMessage() {
		return heartBeatAckMessage;
	}

	public static Message getHeartBeatAck2Message() {
		return heartBeatAck2Message;
	}

	public static Message getNewJobMessage() {
		String messageType = Message.MessageType.JOB_NEW.name();
		Message newJobMessage = new Message(ClusterContext.getLocalAddress(),
				messageType, Message.Verb.JOB_SCHEDULE, new byte[0]);
		return newJobMessage;
	}

	public static Message getNewJobResponseMessage(boolean success,
			String jobControllerIp) {
		String messageType = Message.MessageType.JOB_NEW.name();
		if (!success) {
			messageType = Message.MessageType.JOB_ENDED.name();
			jobControllerIp = "";
		}
		Message response = new Message(ClusterContext.getLocalAddress(),
				messageType, Message.Verb.JOB_NEW, new byte[0]);
		response.setHeader(ClusterConstants.JOB_ROLL.MASTER.name(),
				jobControllerIp.getBytes());
		return response;
	}

	public static Message getShutdownClusterMessage(boolean immediately) {
		String messageType = ClusterConstants.SHUTDOWN_CLUSTER;
		Message shutdown = new Message(ClusterContext.getLocalAddress(),
				messageType, Message.Verb.CLUSTER_MANAGE, new byte[0]);
		return shutdown;
	}

	public static Message getShutdownChildMessage(String masterOrSlaveTag,
			byte[] tagContent) {
		String messageType = ClusterConstants.SHUTDOWN_CHILD;
		Message message = new Message(ClusterContext.getLocalAddress(),
				messageType, Message.Verb.CLUSTER_MANAGE, new byte[0]);
		message.setHeader(masterOrSlaveTag, tagContent);
		return message;
	}

}
